# -*- coding:utf-8 -*-
'''
@author: xiaoming
@contact: lishihui0129@163.com
@time: 2017/6/29 10:34
@desc:
'''
import re
import os
from myUtil import emailPattern,flagSplitPattern
from mysqlHelper import close,insertSql,connectDB

def emailExtract(string):
    '''
    :param string: 待提取对象
    :return:提取结果
    '''

    res=re.findall(emailPattern,string)

    res=list(set(res))

    # flag=prefixFlag(string).strip(" ")

    temp=[]
    for item in res:
        linshi=item
        temp.append(linshi)

    # if len(flag)==0:
    #     for item in res:
    #         linshi="邮箱:"+item+"()"
    #         temp.append(linshi)
    # else:
    #     for item in res:
    #         linshi="邮箱:"+item+"("+flag+")"
    #         temp.append(linshi)
    # return ";".join(temp)
    return temp

def prefixFlag(string):
    '''
    :param string: 待提取对象
    :return:前缀信息
    '''
    string=string.lower()
    # print string
    if '电子' in string:
        ind=string.index('电子')
    elif '信箱' in string:
        ind=string.index('信箱')
    elif '邮箱' in string:
        ind=string.index('邮箱')
    elif 'email' in string:
        ind=string.index('email')
    elif 'e-mail' in string:
        ind=string.index('e-mail')
    elif 'e' in string:
        ind=string.index('e')
    else:
        ind=0
    temp=string[:ind]
    res=re.split(flagSplitPattern,temp)
    return res[-1].strip()

def insertEmailTable(string):
    res=re.findall(emailPattern,string)
    res=list(set(res))
    flag=prefixFlag(string)
    # flag="临时"
    # temp=[]
    connectDB()
    sql="insert into email(email_value,prefix) values(%s,%s)"

    for each in res:
        param=(each,flag)
        insertSql(sql,param)
    close()




if __name__=='__main__':
    workdir='.\output'
    fileList=os.listdir(workdir)
    if 'email.txt' in fileList:
        targetFile=os.path.join(workdir,'email.txt')
        res=open(targetFile).readlines()
        for line in res:
            if '@' in line:
                print emailExtract(line)
                insertEmailTable(line)
            else:
                continue
    else:
        pass